package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static util.Utils.toJacksonJSON;

/**
 * <p>ResponseUtils</p>
 * <p/>
 * <PRE>
 * <BR> 修改记录
 * <BR>-----------------------------------------------
 * <BR> 2016-08-01 youshipeng
 * </PRE>
 *
 * @author youshipeng
 * @version 1.0
 * @since 1.0
 */
public class ResponseUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResponseUtils.class);

    /**
     * <p>返回请求成功的responseBody</p>
     * <p/>
     *
     * @param params data 值
     * @author youshipeng
     * @created 2016-08-01 15:15 PM
     */
    public static Map<String, Object> successData(final Object params) {
        Map<String, Object> result = new HashMap<String, Object>() {{
            put("status", 1);
            put("message", "success");
            put("data", params);
        }};
        return result;
    }

    /**
     * <p>返回请求失败的responseBody</p>
     * <p/>
     *
     * @param errMessage 错误信息
     * @author youshipeng
     * @created 2016-08-01 15:15 PM
     */
    public static Map<String, Object> failureData(final String errMessage) {
        Map<String, Object> result = new HashMap<String, Object>() {{
            put("status", 0);
            put("message", errMessage);
        }};
        return result;
    }

    /**
     * <p>将信息写入response输出流</p>
     * <p/>
     *
     * @author youshipeng
     * @created 2016-08-01 15:15 PM
     */
    public static void writeResponse(HttpServletResponse response, Object result) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(toJacksonJSON(result));
        } catch (IOException e) {
            LOGGER.error("response write error");
            e.printStackTrace();
        } finally {
            Utils.close(out);
        }
    }

    /**
     * <p>将请求失败信息写入response输出流</p>
     * <p/>
     *
     * @author youshipeng
     * @created 2016-08-01 15:15 PM
     */
    public static void writeFailureResponse(HttpServletResponse response, String errMessage) {
        Map<String, Object> result = failureData(errMessage);
        writeResponse(response, result);
    }

    /**
     * <p>将请求成功信息写入response输出流</p>
     * <p/>
     *
     * @author youshipeng
     * @created 2016-08-01 15:15 PM
     */
    public static void writeSuccessResponse(HttpServletResponse response, Object params) {
        Map<String, Object> result = successData(params);
        writeResponse(response, result);
    }
}
